//
//  HomeViewController.m
//  Weibo
//
//  Created by Anasue on 9/9/15.
//  Copyright (c) 2015 Anasue. All rights reserved.
//

#import "HomeViewController.h"
#import "OneViewController.h"
#import "TitleButton.h"
#import "PopMenu.h"
#import "AFNetworking.h"
#import "AccountTool.h"
#import "Account.h"
#import "Status.h"
#import "User.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "LoadMoreFooter.h"
#import "StatusCell.h"
#import "StatusFrame.h"
#import "HttpTool.h"
#import "UserTool.h"
#import "UserInfoParam.h"
#import "UserInfoResult.h"
#import "StatusTool.h"
#import "HomeStatusesParam.h"
#import "HomeStatusesResult.h"
#import "StatusDetailViewController.h"

@interface HomeViewController ()<PopMenuDelegate>
@property (nonatomic, strong) NSMutableArray *statusFrame;
@property (nonatomic, weak) LoadMoreFooter *footer;
@property (nonatomic, weak) TitleButton *titleButton;


@end

@implementation HomeViewController

- (NSMutableArray *)statusFrame
{
    if (_statusFrame == nil) {
        _statusFrame = [NSMutableArray array];
    }
    return _statusFrame;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = Color(211, 211, 211);
    //添加导航栏
    [self setupNavBar];
    
    //添加下拉刷新数据
    [self setupRefresh];
    
    //获得用户名称
    [self setupUserInfo];
    
    //获取通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(linkDidSelected:) name:LinkDidSelectedNotification object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)linkDidSelected:(NSNotification *)note
{
    NSString *linkText = note.userInfo[@"Link"];
    if ([linkText hasPrefix:@"http"]) {
//        UIWebView *webView = [[UIWebView alloc]init];
//        webView.frame = self.view.bounds;
//        [self.view addSubview:webView];
//        NSURL *url = [NSURL URLWithString:linkText];
//        NSURLRequest *request = [NSURLRequest requestWithURL:url];
//        [webView loadRequest:request];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:linkText]];
    }else{
        Log(@"----%@",note.userInfo[@"Link"]);
    }
}

- (void)setupUserInfo
{
    UserInfoParam *params = [UserInfoParam param];
    params.uid = [AccountTool account].name;
    [UserTool userInfoWithParams:params success:^(UserInfoResult *user) {
        //设置名称
        [self.titleButton setTitle:user.name forState:UIControlStateNormal];
        //存储账号信息
        Account *account = [AccountTool account];
        account.name = user.name;
        [AccountTool save:account];
    } failure:^(NSError *error) {
    }];
}

- (void)setupRefresh
{
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc]init];
    [self.tableView addSubview:refreshControl];
    [refreshControl addTarget:self action:@selector(refreshControlStateChange:) forControlEvents:UIControlEventValueChanged];
    //刷新微博
    [refreshControl beginRefreshing];
    [self refreshControlStateChange:refreshControl];
    //添加上拉刷新数据
    LoadMoreFooter *footer = [LoadMoreFooter footer];
    self.tableView.tableFooterView = footer;
    self.footer = footer;
    
}

#pragma mark - 自我刷新
- (void)refresh:(BOOL)fromSelf
{
    if (self.tabBarItem.badgeValue) {
        [self.refreshControl beginRefreshing];
        [self loadNewStatuses:self.refreshControl];
    }else{
        NSIndexPath *firstPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView scrollToRowAtIndexPath:firstPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    
}

#pragma mark - 加载微博数据
- (NSArray *)statusFrameWithStatuses:(NSArray *)statuses
{
    NSMutableArray *frames = [NSMutableArray array];
    for (Status *status in statuses) {
        StatusFrame *frame = [[StatusFrame alloc]init];
        frame.status = status;
        [frames addObject:frame];
    }
    return frames;
}

- (void)refreshControlStateChange:(UIRefreshControl *)refreshControl
{
    [self loadNewStatuses:refreshControl];
}

- (void)loadNewStatuses:(UIRefreshControl *)refreshControl
{
    HomeStatusesParam *param = [HomeStatusesParam param];
    StatusFrame *firstStatusFrame = [self.statusFrame firstObject];
    Status *firstStatus = firstStatusFrame.status;
    if (firstStatus != 0) {
        param.since_id = @([firstStatus.idstr longLongValue]);
    }
    [StatusTool homeStatusesWithParams:param success:^(HomeStatusesResult *result) {
        NSArray *newFrames = [self statusFrameWithStatuses:result.statuses];
        //将新数据插入到旧数据最前面
        NSRange range = NSMakeRange(0, newFrames.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statusFrame insertObjects:newFrames atIndexes:indexSet];
        [self.tableView reloadData];
        [refreshControl endRefreshing];
        //提示用户最新的微博数量
        [self showNewStatusesCount:(int)newFrames.count];
    } failure:^(NSError *error) {
        [refreshControl endRefreshing];
    }];
}

- (void)showNewStatusesCount:(int)count
{
    //1.创建UILable及文字
    UILabel *label = [[UILabel alloc]init];
    if (count) {
        label.text = [NSString stringWithFormat:@"共有%d条新微博数据",count];
    }else
    {
        label.text = @"没有新微博数据";
    }    
    //2.设置label背景颜色
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithName:@"timeline_new_status_background"]];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    //3.设置labelframe
    label.x = 0;
    label.width = self.view.size.width;
    label.height = 35;
    label.y = 64 - label.height;
    //4.添加label到导航控制器上
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    //5.动画显示
    CGFloat duration = 1.0;
    [UIView animateWithDuration:duration animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
    } completion:^(BOOL finished) {
        CGFloat delay = 1.0;
        [UIView animateWithDuration:duration delay:delay options:UIViewAnimationCurveEaseInOut animations:^{
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}

/**
 *  添加微博新数据
 */

- (void)loadMoreStatus
{
    HomeStatusesParam *param = [HomeStatusesParam param];
    StatusFrame *lastStatusFrame = [self.statusFrame lastObject];
    Status *lastStatus = lastStatusFrame.status;
    if (lastStatus) {
        param.max_id = @([lastStatus.idstr longLongValue] - 1);
    }
    [StatusTool homeStatusesWithParams:param success:^(HomeStatusesResult *result) {
        //微博字典数组--》微博模型数组
//        NSArray *statusesDictArray = result.statuses;
//        NSArray *newFrames = [StatusFrame objectArrayWithKeyValuesArray:statusesDictArray];
//        newFrames = [self statusFrameWithStatuses:newFrames];
//        Log(@"%@",result.statuses);
        NSArray *newFrames = [self statusFrameWithStatuses:result.statuses];
        //将新数据插入到旧数据最前面
        [self.statusFrame addObjectsFromArray:newFrames];
        [self.tableView reloadData];
        [self.footer endRefreshing];
    } failure:^(NSError *error) {
        Log(@"%@",error);
        [self.footer endRefreshing];
    }];
}

/**
 *  添加导航栏
 */
- (void)setupNavBar
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" highImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendSearch)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];
    TitleButton *titleButton = [[TitleButton alloc]init];
    NSString *name = [AccountTool account].name;
    [titleButton setTitle:name ? name : @"首页" forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [titleButton setBackgroundImage:[UIImage resizeImage:@"navigationbar_filter_background_highlighted"] forState:UIControlStateHighlighted];
    titleButton.width = 100;
    titleButton.height = 35;
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleButton;
    self.titleButton = titleButton;
}


- (void)titleClick:(UIButton *)titleButton
{
//    UIImage *downImage = [UIImage imageWithName:@"navigationbar_arrow_down"];
//    if (titleButton.currentImage == downImage) {
//        Log(@"up");
        [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
    //弹出菜单
    PopMenu *menu = [PopMenu popMenuWithContentView:nil];
    menu.arrowPosition = PopMenuArrowPositionCenter;
    [menu showInRect:CGRectMake(100, 70, 100, 150)];
    menu.delegate = self;
//    }else{
//        Log(@"down");
//        [titleButton setImage:downImage forState:UIControlStateNormal];
//
//    }
}

#pragma mark - PopMenuDelegate
- (void)popMenuDidDismissed:(PopMenu *)popMenu
{
    TitleButton *titleButton = (TitleButton *)self.navigationItem.titleView;
    [titleButton setImage:[UIImage imageWithName:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
}


- (void)friendSearch
{
    OneViewController *one = [[OneViewController alloc]init];
    [self.navigationController pushViewController:one animated:YES];
}

- (void)pop
{

}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning 监听tableview每次显示数据的过程
    //当没有数据时，tableView的根部视图隐藏
    self.footer.hidden = self.statusFrame.count == 0;
    return self.statusFrame.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StatusCell *cell = [StatusCell cellWithTableView:tableView];
//    cell.textLabel.text = [NSString stringWithFormat:@"主页数据--%ld",indexPath.row];
    cell.statusFrame = self.statusFrame[indexPath.row];
//    cell.backgroundColor = RandomColor;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    StatusDetailViewController *detailVc = [[StatusDetailViewController alloc]init];
    StatusFrame *frame = self.statusFrame[indexPath.row];
    detailVc.status = frame.status;
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StatusFrame *frame = self.statusFrame[indexPath.row];
    return frame.cellHeight;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //1.如果加载的数据小于0，或者正在刷新，就返回
    if (self.statusFrame.count<= 0 || self.footer.isRefreshing)return;
    //2.当footer能显示出来时就刷新上拉状态，并且加载数据
    CGFloat delta = scrollView.contentSize.height - scrollView.contentOffset.y;
    CGFloat sawFooterH = self.view.height - self.tabBarController.tabBar.height;
    if (delta <=sawFooterH - 0) {
        [self.footer beginRefreshing];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self loadMoreStatus];
        });
    }
}

@end
